import Layout from '@components/layout';
import WorkList from '@components/WorkList';
import SearchApi from '@lib/api/search';
import { ISearch } from '@lib/types';
import { Empty, Input, Spin, Typography } from 'antd';
import Router from 'next/router';
import * as React from 'react';

interface ISearchState {
	loading: boolean;
	text?: string;
	result: ISearch[];
}

interface ISearchProps {
	text?: string;
}

class Search extends React.Component<ISearchProps, ISearchState> {
	static getInitialProps(param: any) {
		return {
			text: param.query.text
		}
	}
	constructor(props: any) {
		super(props);
		this.state = {
			text: this.props.text,
			loading: true,
			result: []
		}
	}
	public componentDidMount() {
		this.load(this.state.text);
	}
	public componentWillReceiveProps(props: any) {
		if (props.text !== this.state.text) {
			this.setState({
				text: props.text
			});
			this.load(props.text);
		}
	}
	public async load(text?: string) {
		if (text === "" || typeof(text) === "undefined") {
			this.setState({
				loading: false,
				result: []
			});
			return;
		}
		this.setState({
			loading: true
		});
		const res = await SearchApi(text);
		if (!(res instanceof Error)) {
			this.setState({
				loading: false,
				result: res.list
			});
		}
	}
	public render() {
		const result = this.state.result.length > 0 ? (<WorkList list={this.state.result} hide_vote={true} />) : <Empty />;
		return (
			<Layout title="搜索">
				<div style={{ marginBottom: "8px" }}>
					<Input.Search defaultValue={this.state.text} onSearch={value => Router.push('/search?text=' + value)} placeholder="在这里输入搜索内容"></Input.Search>
				</div>
				<div className="result">
					<Spin spinning={this.state.loading}>{result}</Spin>
				</div>
				<p style={{
					textAlign: "center"
				}}><Typography.Text type="secondary">搜索功能正在测试中，最多显示20条结果</Typography.Text></p>
			</Layout>
		);
	}
}

export default Search;